﻿using System;
using YmtAuth.Domain.Model.YmatouUser;
using YmtAuth.Domain.Repository;
using YmtAuth.Repository.Mongodb;
using YmtSystem.CrossCutting;
using MongoDB.Driver.Builders;

namespace YmtAuth.Repository.YmtAuthDomainRepository
{
    public class UserTokenRepository : Repository_v1<UserToken, string>, IUserTokenRepository
    {
        public UserTokenRepository() : base(new DbContext("TokenMongoUrl")) { }

        public override void Add(UserToken entity, string dbName, string collectionName)
        {
            try
            {
                Context.GetTypeCollection<UserToken>(dbName, collectionName).Insert(entity, MongoDB.Driver.WriteConcern.WMajority);                               
            }
            catch (AggregateException ex)
            {
                foreach (var exItem in ex.InnerExceptions)
                    YmatouLoggingService.Error("保存token异常 {0}", exItem);
            }
            catch (Exception ex)
            {
                YmatouLoggingService.Error("保存token异常: {0}", ex);
            }
        }

        public void RemoveUserToken(int userId)
        {
            this.Context.GetCollection("Ymt_Auth_Token", "UserToken")
                .Remove(Query.EQ("uId", userId));

            this.Context.GetCollection("Ymt_Auth_Token", "UserToken_App")
               .Remove(Query.EQ("uId", userId));

            this.Context.GetCollection("Ymt_Auth_Token", "UserToken_MatouApp")
               .Remove(Query.EQ("uId", userId));
        }
    }
}
